<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮 -->
      <template #toolbar>
        <!-- <a-button
          v-for="(item, index) in butData"
          :key="index"
          :type="item.btnType"
          @click="item.do"
          v-auth="item.auth"
        >
          <Icon v-if="item.icon" :icon="item.icon" /> {{ t(item.title) }}
        </a-button> -->
      </template>
      <!-- 表格插槽 -->
      <template #firstColumn="{ record }">
        <a @click="handleForm({ autoid: record.autoid })">
          {{ record.autoid }}
        </a>
      </template>
    </BasicTable>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      title="采购到货箱码打印"
      @ok="handleModal"
      :width="1000"
    >
      <BasicTable @register="registerPuArrTable" @row-click="handlePuArrRowClick" />
    </BasicModal>
    <PrintModal @register="registerPrintModal" />
    <InputForm @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsWmsPuArrList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, useTable, ActionItem } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import { listSet, customListData } from '/@/api/test/testData';
  import { tabConfigData, schemasData } from '/@/utils/custom';
  import { u8WmsPuArrDelete } from '/@/api/wms/pu/arr/u8WmsPuArr';
  import PrintModal from '/@/components/print/printModal.vue';

  const { t } = useI18n('sys.role');

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 4, md: 6 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('采购到货管理'),
  });
  let title = ref('');

  const [registerTable, { reload, setProps, getSelectRows }] = useTable({
    //actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });

  const [registerModal, { openModal, closeModal }] = useModal();
  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();

  onMounted(async () => {
    const res = await listSet({ viewCode: 'pu_arr_list001' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey === 'btnPrintBox') {
        item.do = () => handlePrintBoxCode({});
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        for (const key in params) {
          if (Array.isArray(params[key])) {
            params[key + '_gte'] = params[key][0];
            params[key + '_lte'] = params[key][1];
            delete params[key];
          }
        }
        params.url = listTabConfig.value.api;
        return params;
      },
    });

    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  const tableColumnsPrint: BasicColumn[] = [
    {
      title: t('存货编码'),
      dataIndex: 'cinvcode',
      key: 'a.cinvcode',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'basInv.cinvname',
      key: 'a.cinvname',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      key: 'a.cinvstd',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('数量'),
      dataIndex: 'iqty',
      key: 'a.iqty',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('打印张数'),
      dataIndex: 'counts',
      key: 'a.counts',
      sorter: true,
      width: 130,
      align: 'center',
      editable: true,
      edit: true,
      editRow: true,
      editComponent: 'InputNumber',
      // editDefaultValue: '1',
      editComponentProps: {
        maxlength: 16,
      },
      editRule: true,
    },
  ];

  const [registerPuArrTable, boxCodePrintTable] = useTable({
    columns: tableColumnsPrint,
    rowKey: 'id',
    pagination: false,
    bordered: true,
  });

  async function handleDelete(record: Recordable) {
    const res = await u8WmsPuArrDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  function handlePuArrRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function getBoxCodeList() {
    let boxCodeValid = true;
    let boxCodeList: Recordable[] = [];
    for (const record of boxCodePrintTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        boxCodeValid = false;
      }
      boxCodeList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of boxCodePrintTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      boxCodeList.push({
        ...record,
        status: '1',
      });
    }
    if (!boxCodeValid) {
      throw { errorFields: [{ name: ['boxCodeList'] }] };
    }
    return boxCodeList;
  }

  // 箱码打印
  async function handlePrintBoxCode() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    await openModal(true, {});
    arr.forEach((element) => {
      element.counts = 1;
    });
    boxCodePrintTable.setTableData(arr);
  }

  // 箱码打印
  async function handleModal() {
    const data = await getBoxCodeList();
    let params = {
      ids: '',
      counts: '',
      title: '采购到货箱码打印',
      height: '0.9',
      width: '0.9',
      fileName: '采购到货箱码打印',
    };
    data.forEach((e) => {
      params.ids += e.id + ',';
      params.counts += e.counts + ',';
    });
    params.ids = params.ids.substring(0, params.ids.length - 1);
    params.counts = params.counts.substring(0, params.counts.length - 1);
    openPrintModal(true, params);
    closeModal();
    boxCodePrintTable.setTableData([]);
  }

  function handleSuccess() {
    reload();
  }
</script>
<style scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
